
# -*- coding: utf-8 -*-
import sys
import os
import pyaudio
import tempfile
import wave
import audioop
import Queue as queue
import logging
from  source.etms_source import etmsSource
logger=logging.getLogger(__name__)
class Mic(object):
    def __init__(self):
        self.speaker=etmsSource()

        # self.put=self.speaker.put;
        self.speaker.link(self)


        self.listingKwd=False
        self.listing=False
        self.startDone=False
        self.kwdSay=False
        self.audio_queue=queue.Queue(maxsize=1000)

    def getScore(self, data):
        rms = audioop.rms(data, 2)
        score = rms / 3
        return score

    def put(self,data):
        if self.listing:
            self.audio_queue.put(data)
    def start(self):
        self.speaker.start()
        self.startDone=True

    def on_detected(self):
        self.kwdSay=True

    def passKWD(self):
        if not self.startDone:
            return False

        self.listingKwd=True
        self.listing=False
        self.kwdSay=False
        while self.listingKwd:
            if self.kwdSay:
                self.listingKwd=False
                self.kwdSay=False
                logger.info(u"唤醒了...")
                return True

        return False

    def gen(self,timeout=10000):
        time_elapsed = 0
        while self.listening and time_elapsed <= timeout:
            try:
                chunk = self.audio_queue.get(timeout=1.0)
            except queue.Empty:
                break

            yield chunk
            time_elapsed += len(chunk) * 1000 / (2 * 16000)  # 16000 fs, 2 bytes width
            logger.debug('Sending chunk, time_elapsed = {}'.format(time_elapsed))

    def activeListenToAllOptions(self, THRESHOLD=None, LISTEN=True,
                                 MUSIC=False,pixels=None):
        if not self.startDone:
            return None

        RATE = 16000
        self.listingKwd=False
        self.pixels=pixels
        self.audio_queue.queue.clear()
        # self.beforeListen();
        self.listing=True
        attachment=self.gen()
        frames = []
        for chunk in attachment:
            frames.append(chunk)


        with tempfile.SpooledTemporaryFile(mode='w+b') as f:
            wav_fp = wave.open(f, 'wb')
            wav_fp.setnchannels(1)
            wav_fp.setsampwidth(pyaudio.get_sample_size(pyaudio.paInt16))
            wav_fp.setframerate(RATE)
            wav_fp.writeframes(''.join(frames))
            wav_fp.close()
            f.seek(0)
            self.listing=False
            return f










